import 'dart:convert' as JSON;
import 'dart:math';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart' as prefix;

import '../constants.dart' show AppColors, AppStyles, Constants;
import 'conversation_detail_args.dart';

class ConversationDetailPage extends StatefulWidget {
  @override
  _ConversationDetailPageState createState() => _ConversationDetailPageState();
}

class _ConversationDetailPageState extends State<ConversationDetailPage> {
  final maxChatBoxLinesForDisplay = 4;
  final _controller = TextEditingController();
  FocusNode _focusNode = FocusNode();

  // ignore: unused_element
  void _sendMessageAddSendUserInfo() async {
    prefix.TextMessage msg = new prefix.TextMessage();
    msg.content = "测试文本消息携带用户信息";
    /*
  测试携带用户信息
  */
    prefix.UserInfo sendUserInfo = new prefix.UserInfo();
    sendUserInfo.name = "textSendUser.name";
    sendUserInfo.userId = "textSendUser.userId";
    sendUserInfo.portraitUri = "textSendUser.portraitUrl";
    msg.sendUserInfo = sendUserInfo;

    prefix.Message message = await prefix.RongIMClient.sendMessage(
        prefix.RCConversationType.Private, "SealTalk", msg);
    print("发送文本信息显示用户信息:" +
        message.content.getObjectName() +
        " 文本内容:" +
        message.content.encode());
  }

  @override
  Widget build(BuildContext context) {
    // 接收conversation_page页面传递过来（title,avatar）的数据
    final ConversationDetailArgs args =
        ModalRoute.of(context).settings.arguments;

    // 接受网络请求后的结果数据
    getHttp()
        // ignore: unnecessary_brace_in_string_interps
        .then((result) => {print('接口返回的数据是：${result.data}')})
        .whenComplete(() => {print('异步任务处理完成')})
        // ignore: unnecessary_brace_in_string_interps
        .catchError((err) => {print('出现异常了,${err}')});

    // TextMessage txtMessage = new TextMessage();
    // txtMessage.content = "这条消息来自 Flutter";
    // Message msg = await prefix.RongIMClient.sendMessage(RCConversationType.Private,privateUserId,txtMessage);

    return Scaffold(
        appBar: PreferredSize(
          child: AppBar(
            title: Text(
              args.title,
              style: AppStyles.HeadTitlteStyle,
            ),
            leading: IconButton(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: Icon(
                IconData(
                  0xe610,
                  fontFamily: Constants.IconFontFamily,
                ),
                size: Constants.ActionIconSize + 4.0,
                color: const Color(AppColors.ActionIconColor),
              ),
            ),
            elevation: 0.0,
            brightness: Brightness.light,
            backgroundColor: const Color(AppColors.AppBarColor),
            actions: [
              IconButton(
                onPressed: () {
                  print('打开显示更多下来菜单');
                },
                icon: Icon(
                  IconData(
                    0xe65d,
                    fontFamily: Constants.IconFontFamily,
                  ),
                  size: Constants.ActionIconSize + 4.0,
                  color: const Color(AppColors.ActionIconColor),
                ),
              ),
              SizedBox(width: 5.0),
            ],
            centerTitle: true,
          ),
          preferredSize: Size.fromHeight(50.0), //70
        ),
        body: Column(
          children: <Widget>[
            // 聊天对话
            Expanded(
              child: Container(
                child: ChatDetailList(),
                decoration: BoxDecoration(
                  color: const Color(AppColors.AppBarColor),
                  border: Border(
                      top: BorderSide(
                        color: const Color(AppColors.BorderColor),
                        width: 1.0,
                      ),
                      bottom: BorderSide(
                          color: const Color(AppColors.ConversationBorderColor),
                          width: 2.0)),
                ),
              ),
            ),
            // 底部栏
            Container(
              color: const Color(AppColors.ConversationInputBgColor),
              constraints: BoxConstraints(
                minHeight: 40.0,
                maxHeight: 110.0,
              ),
              child: Row(
                // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  IconButton(
                    onPressed: () {
                      print('语音文字切换');
                    },
                    padding: const EdgeInsets.only(bottom: 10.0),
                    icon: Icon(
                      IconData(
                        0xe7e2,
                        fontFamily: Constants.IconFontFamily,
                      ),
                      size: Constants.ActionIconSize + 18.0,
                      color: const Color(AppColors.ActionIconColor),
                    ),
                  ),
                  Expanded(
                    child: Container(
                      // height: Constants.InputHeight - 10,
                      margin: const EdgeInsets.symmetric(
                        horizontal: 5.0,
                        vertical: 8.0,
                      ),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(5.0)),
                      constraints: BoxConstraints(
                        minHeight: 20.0,
                        maxHeight: 100.0,
                      ),
                      // LayoutBuilder是在Layout的阶段会回调一个函数
                      child: TextField(
                        maxLines: 1,
                        keyboardType: TextInputType.multiline,
                        decoration: InputDecoration(
                          border: InputBorder.none,
                          contentPadding: const EdgeInsets.all(10.0),
                          hintStyle: TextStyle(fontSize: 14.0),
                          isDense: true,
                        ),
                        controller: _controller,
                        cursorColor: Color(AppColors.TabIconActive),
                        focusNode: _focusNode,
                        onChanged: (val) {
                          // setState(() {
                          //   var selection;
                          //   var editoLastCursor =
                          //       _textEditingController.selection.baseOffset;
                          // });
                          print('$val');
                        },
                        onTap: () => {handleEditorTaped()},
                      ),
                    ),
                  ),
                  IconButton(
                    onPressed: () {
                      print('表情包');
                    },
                    padding: const EdgeInsets.only(bottom: 10.0, right: 0.0),
                    icon: Icon(
                      IconData(
                        0xe60b,
                        fontFamily: Constants.IconFontFamily,
                      ),
                      size: Constants.ActionIconSize + 16.0,
                      color: const Color(AppColors.ActionIconColor),
                    ),
                  ),
                  IconButton(
                    onPressed: () {
                      print('显示更多功能');
                    },
                    padding: const EdgeInsets.only(bottom: 10.0, left: 1.0),
                    icon: Icon(
                      IconData(
                        0xe618,
                        fontFamily: Constants.IconFontFamily,
                      ),
                      size: Constants.ActionIconSize + 20.0,
                      color: const Color(AppColors.ActionIconColor),
                    ),
                  ),
                ],
              ),
            )
          ],
        ));
  }

  // 当输入框被点击时，回调该函数
  handleEditorTaped() {
    print('被点击了！');
  }
}

class ChatRecord {
  int sender;
  String content;
  String avatarUrl;
  ChatRecord({this.sender, this.content, this.avatarUrl});
}

/// 聊天详情列表数据
class ChatDetailList extends StatelessWidget {
  const ChatDetailList({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double rpx = MediaQuery.of(context).size.width / 750;
    // 接收conversation_page页面传递过来（title,avatar）的数据
    final ConversationDetailArgs args =
        ModalRoute.of(context).settings.arguments;

    // 自己 本人发送 self 0 的头像
    String ava1 = 'assets/images/avatar.jpg';
    // 其他发送者 other 1 的头像
    String ava2 = args.avatar;
    List<ChatRecord> records = List<ChatRecord>();
    // 聊天列表数据
    records.add(ChatRecord(avatarUrl: ava2, content: '你好', sender: 1));
    records.add(ChatRecord(avatarUrl: ava1, content: '你好啊！', sender: 0));
    records
        .add(ChatRecord(avatarUrl: ava1, content: 'HelloWorld!~~~', sender: 0));
    records.add(
        ChatRecord(avatarUrl: ava1, content: '🖊and🍎,applepen', sender: 0));
    records.add(
        ChatRecord(avatarUrl: ava2, content: '我叫${args.title}', sender: 1));
    records.add(ChatRecord(
        avatarUrl: ava1, content: '很高心能够认识你，${args.title}', sender: 0));
    records.add(ChatRecord(avatarUrl: ava2, content: '我来自广东深圳', sender: 1));
    records.add(ChatRecord(avatarUrl: ava2, content: '你呢', sender: 1));
    records.add(ChatRecord(avatarUrl: ava1, content: '我来自广东汕头 嘿嘿', sender: 0));
    records.add(ChatRecord(avatarUrl: ava1, content: '深圳是个很不错的地方呢', sender: 0));
    records.add(ChatRecord(avatarUrl: ava2, content: '哈哈', sender: 1));
    records.add(ChatRecord(avatarUrl: ava2, content: '嘻嘻', sender: 1));
    records.add(ChatRecord(
        avatarUrl: ava1, content: 'niceeeeeeeeeeeeeeeeee', sender: 0));
    records.add(ChatRecord(avatarUrl: ava1, content: '哈哈哈', sender: 0));
    records.add(ChatRecord(avatarUrl: ava1, content: '你吃饭了🐎', sender: 0));
    return Container(
      child: ListView.builder(
        itemBuilder: (context, index) {
          return ChatRow(
              sender: records[index].sender,
              content: records[index].content,
              avatarUrl: records[index].avatarUrl);
        },
        itemCount: records.length,
      ),
    );
  }
}

///时间戳(居中)
class TimeRow extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double rpx = MediaQuery.of(context).size.width / 750;
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10.0 * rpx),
      child: Text(
        '昨天 下午4:03',
        style: AppStyles.TimeTextStyle,
        textAlign: TextAlign.center,
      ),
    );
  }
}

///聊天框（头像+聊天框+三角形）
class ChatRow extends StatelessWidget {
  const ChatRow(
      {Key key,
      @required this.sender,
      @required this.content,
      @required this.avatarUrl})
      : super(key: key);

  final int sender; // 发送者： 0 self(自己) 1 other(其他发送者)
  final String content; //发送内容
  final String avatarUrl; //用户头像url

  @override
  Widget build(BuildContext context) {
    double rpx = MediaQuery.of(context).size.width / 750;
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10 * rpx, horizontal: 20 * rpx),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment:
            sender == 1 ? MainAxisAlignment.start : MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          sender == 1
              // 左侧（other）发送者头像
              ? Center(
                  child: Container(
                    // 头像框大小
                    width: 80 * rpx,
                    height: 80 * rpx,
                    child: ClipRRect(
                        // 头像框圆角
                        borderRadius: BorderRadius.circular(6 * rpx),
                        // 头像url
                        child: avatarUrl.indexOf('http') == 0 ||
                                avatarUrl.indexOf('https') == 0
                            ? Image.network(
                                avatarUrl,
                                fit: BoxFit.cover,
                              )
                            : Image.asset(
                                avatarUrl,
                                fit: BoxFit.cover,
                              )),
                  ),
                )
              : Container(),
          sender == 1
              ? Container(
                  width: 10 * rpx,
                )
              : Container(),
          // CustomPaint绘制一个聊天框
          sender == 1
              ? Container(
                  padding: EdgeInsets.only(bottom: 35 * rpx),
                  child: CustomPaint(
                    painter: ChatBoxPainter(
                      color: Colors.white,
                      width: 10 * rpx,
                      height: 15 * rpx,
                    ),
                  ),
                )
              : Container(),
          Container(
            padding: EdgeInsets.all(20 * rpx),
            margin: sender == 1
                ? EdgeInsets.only(left: 10 * rpx)
                : EdgeInsets.only(right: 10 * rpx),
            height: 80 * rpx,
            alignment: Alignment.center,
            child: Text(
              content,
              style: AppStyles.ConversationDetailTextStyle,
              textAlign: sender == 1 ? TextAlign.left : TextAlign.right,
            ),
            decoration: BoxDecoration(
              color: sender == 1
                  ? Colors.white
                  : Color(AppColors.ConversationDetailBgColor),
              borderRadius: BorderRadius.circular(10 * rpx),
            ),
          ),
          // 向右的箭头 初始组件是左箭头，所以需要旋转180度
          sender == 0
              ? Transform.rotate(
                  angle: pi,
                  child: Container(
                    padding: EdgeInsets.only(top: 10 * rpx),
                    child: CustomPaint(
                      painter: ChatBoxPainter(
                        color: Color(AppColors.ConversationDetailBgColor),
                        width: 10 * rpx,
                        height: 15 * rpx,
                      ),
                    ),
                  ),
                )
              : Container(),
          sender == 0
              ? Container(
                  width: 10 * rpx,
                )
              : Container(),
          sender == 0
              // 右侧（self）发送者头像
              ? Center(
                  child: Container(
                    // 头像框大小
                    width: 80 * rpx,
                    height: 80 * rpx,
                    child: ClipRRect(
                        // 头像框圆角
                        borderRadius: BorderRadius.circular(6),
                        // 头像url
                        child: avatarUrl.indexOf('http') == 0 ||
                                avatarUrl.indexOf('https') == 0
                            ? Image.network(
                                avatarUrl,
                                fit: BoxFit.cover,
                              )
                            : Image.asset(
                                avatarUrl,
                                fit: BoxFit.cover,
                              )),
                  ),
                )
              : Container(),
        ],
      ),
    );
  }
}

/// 聊天框三角形
class ChatBoxPainter extends CustomPainter {
  // 构造函数
  ChatBoxPainter(
      {@required this.width, @required this.height, @required this.color});
  final double width;
  final double height;
  final Color color;

  @override
  void paint(Canvas canvas, Size size) {
    // 利用canvas画出三个顶点的坐标 path是一个顶点在左侧的聊天三角形
    Path path = Path()
      ..moveTo(0, height / 2) //顶点坐标
      ..lineTo(width, height)
      ..lineTo(width, 0)
      ..lineTo(0, height / 2);

    // paint（画笔）
    Paint paint = Paint()
      ..style = PaintingStyle.fill //填充
      ..color = color; //颜色

    canvas.drawPath(path, paint);
  }

  // 不需要重新绘制
  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

///请求接口获取数据
Future<Response> getHttp() async {
  // test
  String url = "http://v.juhe.cn/toutiao/index";
  String key = "4c52313fc9247e5b4176aed5ddd56ad7";
  String type = "keji";

  print('开始请求数据');
  Response response =
      await Dio().get(url, queryParameters: {"type": type, "key": key});

  print('请求完成');

  return response;
}
